package com.ftg.learn.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kangjx
 * @createTime 2022/12/28
 */
@RestController
//cros  : 解决跨域问题 , 就是在springboot 的restful api层添加一个注解
// 通过注解来配置白名单 : 存在白名单里面的ip地址可以跨域
//@CrossOrigin(value = "http://192.168.0.143:3000/")
// 面试 ： 1 ：  cros   通过网关，通过springboot crosorign
// 2 : 官网 springboot [问题难点]

public class DemoController {

    /**
     * 我们使用代码方式完成了这次请求
     * @return
     */
    @GetMapping("/hello")
//    @SentinelResource(value = "h1",entryType = )
    public String h1(){
        try (Entry entry = SphU.entry("HelloWorld")) {
            // 被保护的逻辑
            System.out.println("hello world");
            return "{\"code\":200,\"msg\":\"you see\",\"data\":[]}";
        } catch (BlockException ex) {
            // 处理被流控的逻辑
            System.out.println("blocked!");
            return "对不起，当前商品已售罄！！hello8082catch";
        }
    }

    /**
     * 这个是我们的规则
     */
    @PostConstruct
    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("HelloWorld");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(1);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

    @GetMapping("/first")
    /**
     * value : 资源名称
     * blockHandler : 限流
     * fallback : 降级
     */
    @SentinelResource(value = "hello", blockHandler = "exceptionHandler", fallback = "helloFallback")
    public String hello() {
        return String.format("Hello at %d","正常执行方法!!!");
    }

    public String helloFallback() {
        return String.format("Halooooo %d", "出错了，限流了");
    }

    public static String exceptionHandler(BlockException ex) {
        // Do some log here.
        ex.printStackTrace();
        return "Oops, error occurred at  我被降级了";
    }
    /**
     * 1 ：  完成对sentinel 控制台的下载启动
     * 2 : 查看里面的节点和功能，创建一个规则
     * 3 : 启动我们的spring boot 查看规则 是否可用
     */

}
